package com.ruiben.mall.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruiben.mall.IOrderService;
import com.ruiben.mall.mapper.*;
import com.ruiben.mall.pojo.*;
import com.ruiben.mall.utils.PagedResult;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ruiben.mall.config.Config.BASE_URL;


@Service
public class OrderServiceImpl implements IOrderService {


    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private UserOrderProductMapper userOrderProductMapper;

    @Autowired
    private UserOrderBackMapper userOrderBackMapper;

    @Autowired
    private UserBackProductMapper userBackProductMapper;

    @Autowired
    private UserCartMapper userCartMapper;

    @Autowired
    private Sid sid;

    /**
     * 插入订单
     * orderstatus 订单状态（1未付款2已付款3已发货4待评价5已评价6退换货7取消订单）
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UserOrder addOrder(String userId, String[] cartIds,String addressId) {

        UserOrder userOrder = new UserOrder();
        userOrder.setId(sid.nextShort());


        BigDecimal total = new BigDecimal(0);

        for (String cartId:cartIds){
            UserCart cartInfo = userCartMapper.getCartInfo(cartId);
            UserOrderProduct userOrderProduct = new UserOrderProduct();
            userOrderProduct.setId(sid.nextShort());
            userOrderProduct.setOrderid(userOrder.getId());
            userOrderProduct.setProductid(cartInfo.getShopProduct().getId());
            userOrderProduct.setProductname(cartInfo.getShopProduct().getProductname());
            userOrderProduct.setProductnum(cartInfo.getProductnum());
            userOrderProduct.setProductphoto(cartInfo.getShopProduct().getImagePath());
            userOrderProduct.setProductprice(cartInfo.getShopProduct().getPrice());
            userOrderProduct.setProductattrname(cartInfo.getProductAttrName());
            userOrderProduct.setIscomment((short)0);
            userOrderProductMapper.insert(userOrderProduct);

            total = total.add(new BigDecimal(cartInfo.getProductPrice()*cartInfo.getProductnum()));

            //删除购物车
            userCartMapper.deleteByPrimaryKey(cartId);
        }


        userOrder.setSumprice(total);
        userOrder.setUserid(userId);
        userOrder.setOrderno(sid.nextShort());
        userOrder.setOrdertime(new Date());
        userOrder.setOrderstatus((short)1);

        //获取用户地址
        UserAddress address = userAddressMapper.selectByPrimaryKey(addressId);
        userOrder.setConsigneeprovince(address.getProvince());
        userOrder.setConsigneecity(address.getCity());
        userOrder.setConsigneearea(address.getArea());
        userOrder.setConsigneeaddress(address.getAddress());
        userOrder.setConsigneephone(address.getPhone());
        userOrder.setConsigneeusername(address.getName());
        userOrder.setUseraddressid(addressId);

        userOrderMapper.insert(userOrder);


        return userOrder;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean confirmOrder(String userAddressId, String orderId,int paytype,String orderContent) {

        UserOrder userOrder = new UserOrder();

        //获取用户的收货地址
        Example example = new Example(UserAddress.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",userAddressId);
        UserAddress userAddress = userAddressMapper.selectOneByExample(example);
        userOrder.setOrderstatus((short)2);
        userOrder.setPaytype((short)paytype);
        userOrder.setId(orderId);
        userOrder.setConsigneeusername(userAddress.getName());
        userOrder.setConsigneephone(userAddress.getPhone());
        userOrder.setConsigneeprovince(userAddress.getProvince());
        userOrder.setConsigneecity(userAddress.getCity());
        userOrder.setConsigneearea(userAddress.getArea());
        userOrder.setOrdercontent(orderContent);
        userOrder.setConsigneeaddress(userAddress.getAddress());

        int insert = userOrderMapper.updateByPrimaryKeySelective(userOrder);



        return insert>0;
    }


    /**
     * 更新订单
     * orderstatus 订单状态（1未付款2已付款3已发货4待评价5已评价6退换货7取消订单）
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean updateOrderProduct(String orderId, List<UserOrderProduct> userOrderProducts, BigDecimal productTotal) {

        for (UserOrderProduct product:userOrderProducts){
            userOrderProductMapper.updateByPrimaryKeySelective(product);
        }

        UserOrder userOrder = new UserOrder();
        userOrder.setId(orderId);
        userOrder.setSumprice(productTotal);
        userOrderMapper.updateByPrimaryKeySelective(userOrder);

        return true;
    }

    /**
     * 根据订单id获取详细订单
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public UserOrder getOrderById(String orderId) {
        return userOrderMapper.selectByPrimaryKey(orderId);
    }


    /**
     * 根据订单id获取详细订单
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public UserOrder getOrderById(String orderId,String orderNo) {
        Example example = new Example(UserOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",orderId);
        criteria.andEqualTo("orderno",orderNo);
        return userOrderMapper.selectOneByExample(example);
    }

    @Override
    public UserOrder getOrderByOrderNo(String orderNo) {
        Example example = new Example(UserOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderno",orderNo);
        UserOrder userOrder = userOrderMapper.selectOneByExample(example);
        return userOrder;
    }


    /**
     * 根据用户id获取订单
     */
    @Override
    public PagedResult getOrderList(String userId, int page, int pageSize) {
        PageHelper.startPage(page,pageSize);
        List<UserOrder> admins = userOrderMapper.getAllUserOrderListForUserId(userId);
        PageInfo<UserOrder> pageList = new PageInfo<>(admins);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(admins);
        pagedResult.setRecords(pageList.getTotal());
        return pagedResult;
    }

    /**
     * 根据用户id获取订单
     */
    @Override
    public PagedResult getOrderListForStatus(String userId, int status, int page, int pageSize) {
        PageHelper.startPage(page,pageSize);
        List<UserOrder> admins = userOrderMapper.getUserOrderListByStatus(status,userId);
        PageInfo<UserOrder> pageList = new PageInfo<>(admins);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(admins);
        pagedResult.setRecords(pageList.getTotal());
        return pagedResult;
    }


    @Override
    public UserOrder getOrderDetailById(String id,int status) {
        UserOrder orderDetail= userOrderMapper.getOrderDetailById(id,status);
        if (orderDetail == null) {
            return null;
        }
        List<UserOrderProduct> orderProduct = orderDetail.getOrderProduct();
        if (orderProduct == null) {
            return null;
        }
        for (UserOrderProduct product:orderProduct){
            product.setProductphoto(BASE_URL + product.getProductphoto());
        }
        return orderDetail;
    }

    /**
     * 退换货
     * @param back
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean returnGoods(UserOrderBack back,String goodId) {

        //插入定单
        back.setId(sid.nextShort());

        //根据商品id获取订单中的商品
        Example example = new Example(UserOrderProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productid",goodId);
        criteria.andEqualTo("orderid",back.getOrderid());
        UserOrderProduct userOrderProduct = userOrderProductMapper.selectOneByExample(example);


        //插入退货与售后中的商品数据
        UserBackProduct userBackProduct = new UserBackProduct();
        userBackProduct.setOrderid(back.getOrderid());
        userBackProduct.setProductid(userOrderProduct.getProductid());
        userBackProduct.setProductname(userOrderProduct.getProductname());
        userBackProduct.setProductnum(1);
        userBackProduct.setProductprice(userOrderProduct.getProductprice());
        userBackProduct.setProductphoto(userOrderProduct.getProductphoto());
        userBackProduct.setId(sid.nextShort());
        userBackProduct.setOrderbackid(back.getId());
        userBackProduct.setProducttype(userOrderProduct.getProducttype());
        userBackProductMapper.insert(userBackProduct);



        userOrderBackMapper.insert(back);
        return true;
    }

    /**
     * 获取退换货列表
     * @return
     */
    @Override
    public PagedResult getUserOrderBackList(int page, int pageSize, Integer orderBackStatus) {
        PageHelper.startPage(page,pageSize);
        List<UserOrderBack> orderBacks;
        if (orderBackStatus == null){

            orderBacks = userOrderBackMapper.getOrderBackList();
        } else {
            orderBacks = userOrderBackMapper.getOrderBackListByStatus(orderBackStatus);

        }
        PageInfo<UserOrderBack> pageList = new PageInfo<>(orderBacks);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(orderBacks);
        pagedResult.setRecords(pageList.getTotal());
        return pagedResult;
    }

    @Override
    public UserOrderBack getUserOrderBackDetailById(String id) {
        return userOrderBackMapper.getUserOrderBackDetailById(id);
    }

    @Override
    public boolean finishOrderBack(UserOrderBack userOrderBack) {

        int i = userOrderBackMapper.updateByPrimaryKeySelective(userOrderBack);

        return i>0;
    }


    public boolean updateOrder(UserOrder order){
        return userOrderMapper.updateByPrimaryKeySelective(order) > 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean delOrder(String id){
        int i = userOrderMapper.deleteByPrimaryKey(id);
        return i>0;
    }

    @Override
    public UserOrder getCommentGoodsList(String orderId) {
        UserOrder orderDetailById = userOrderMapper.getOrderDetailById(orderId, 4);
        List<UserOrderProduct> orderProducts = orderDetailById.getOrderProduct();
        if (orderProducts == null||orderProducts.size()==0){
            return null;
        }
        List<UserOrderProduct> commentGoods = new ArrayList<>();
        for (UserOrderProduct product:orderProducts){
            if (product.getIscomment() == null || product.getIscomment() == 0){
                product.setProductphoto(BASE_URL + product.getProductphoto());
                commentGoods.add(product);
            }
        }
        orderDetailById.setOrderProduct(commentGoods);
        return orderDetailById;
    }

}
